package edu.must.uh.servlet;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.must.uh.impl.SharesImpl;
import edu.must.uh.util.CellFormat;
import edu.must.uh.util.HttpClientResult;
import edu.must.uh.util.HttpClientUtils;
import edu.must.uh.util.R;
import edu.must.uh.util.ServletUtils;
import edu.must.uh.util.Tools;
import edu.must.uh.util.ToolsOfString;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@WebServlet("/SharesAnalysisServlet")
public class SharesAnalysisServlet extends BaseServlet {
    
    private static final long serialVersionUID = 12197442526341123L;
    private static Logger logger = Logger.getLogger(RegCodeServlet.class); 
    SharesImpl baseImpl = new SharesImpl();    
    
    public Object getList(HttpServletRequest request, HttpServletResponse response) throws Exception {      
        
        String START_DATE =ToolsOfString.NulltoEmpty(request.getParameter("START_DATE")).replace("-", ""); 
        String END_DATE =ToolsOfString.NulltoEmpty(request.getParameter("END_DATE")).replace("-", ""); 
        SharesImpl sharesImpl = new SharesImpl();
        List<Map<String,Object>>  sharesList  =  sharesImpl.getSelect();
        for (Map<String, Object> sharesMap : sharesList) {
            String sharesid =ToolsOfString.NulltoEmpty(sharesMap.get("SHAREID")) ;
            if(sharesid.startsWith("6")) {
                sharesid = "sh"+sharesid;
           }else {
               sharesid = "sz"+sharesid; 
           } 
           sharesMap.put("CODE", sharesid);        
        }
        String url = "http://hq.sinajs.cn/list=sh603259";
        for (Map<String,Object> sharesMap:sharesList) {
            url = url +","+ToolsOfString.NulltoEmpty(sharesMap.get("CODE")) ;
        } 
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8"); 
        HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
        if (result.getCode() == 200) { 
            String[] Contents = result.getContent().toString().split(";");
            for (int i = 1; i < Contents.length-1; i++) {
                String sContent = Contents[i];
                Map<String,Object> e =  sharesList.get(i-1);
                
                String[] Content = sContent.split("=\"")[1].split(",");
                Float price = Float.parseFloat(Content[3]);
                Float yesterdayClose = Float.parseFloat(Content[2]);
                e.put("name", Content[0]);
                e.put("price", price);
                e.put("balance",String.format("%.2f",  price -yesterdayClose));
            }
        }   
        String sUrlString = "cn_603259";
        for (Map<String, Object> sharesMap : sharesList) {
            String sharesid =ToolsOfString.NulltoEmpty(sharesMap.get("SHAREID")) ;
            sUrlString =sUrlString +",cn_"+ sharesid;
        }
        url = "https://q.stock.sohu.com/hisHq?code=cn_"+sUrlString+"&start="+START_DATE+"&end="+END_DATE ;        
        result = HttpClientUtils.doGet(url, params, null); 
        if (result.getCode() == 200) {             
           
            JSONArray arr = JSONArray.parseArray(result.getContent());
            for (int i = 1; i < arr.size(); i++) { 
                JSONObject ob = arr.getJSONObject(i);
                Map<String,Object> e =  sharesList.get(i-1);
                JSONArray arrhq =JSONArray.parseArray(ob.getString("hq"));
                if(arrhq!=null && !arrhq.isEmpty()) {
                    Double closeDouble = 0.0;
                    Integer arrhqSize = arrhq.size();
                    List<Double> doubleList = new ArrayList<Double>();
                    
                    for (int j = 0; j < arrhqSize; j++) {                       
                       String hqs = arrhq.getString(j).replace("[", "").replace("]", "").replace("\"", "");
                       String[] eStrings = hqs.split(",");
                       Double _closeDouble = Double.parseDouble(eStrings[2]);
                       doubleList.add(_closeDouble);
                       closeDouble = closeDouble + _closeDouble;
                    }   
                    double average = closeDouble/arrhqSize;  
                    e.put("ave", String.format("%.2f", average));                    
                
                    int total=0;
                    for(Double s:doubleList){
                        total += (s-average)*(s-average);   //求出方差，如果要计算方差的话这一步就可以了
                    }
                    double standardDeviation = Math.sqrt(total/arrhqSize);   //求出标准差                    
                    e.put("standardDeviation", String.format("%.2f", standardDeviation)); 
                }
            }
        }            
       
        return R.succ(sharesList);         
    }
    
    public Object getList2(HttpServletRequest request, HttpServletResponse response) throws Exception {      
     
        String START_DATE =ToolsOfString.NulltoEmpty(request.getParameter("START_DATE")).replace("-", ""); 
        String END_DATE =ToolsOfString.NulltoEmpty(request.getParameter("END_DATE")).replace("-", ""); 
        String SHAREID =ToolsOfString.NulltoEmpty(request.getParameter("SHAREID")); 
                
        List<Map<String,Object>> resList = new ArrayList<Map<String,Object>>();
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");             
        String url = "https://q.stock.sohu.com/hisHq?code=cn_"+SHAREID+"&start="+START_DATE+"&end="+END_DATE ;        
        HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
        if (result.getCode() == 200) { 
            
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition" , "attachment ; filename = Export Data.xls " );  
            OutputStream os = response.getOutputStream();
            WritableWorkbook workbook = Workbook.createWorkbook(os);
            WritableSheet worksheet= workbook.createSheet("Data", 0); 
            Integer colInteger = 0;
            Integer rowInteger = 0;
            worksheet.addCell(new Label(colInteger++, rowInteger,"日期" , CellFormat.getCellFormat()));   
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日开盘价", CellFormat.getCellFormat()));         
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日收盘价", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"涨跌幅度 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"涨跌百分比 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日最低价 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日最高价 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日成交股票手数 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"今日成交金额 ", CellFormat.getCellFormat()));
            worksheet.addCell(new Label(colInteger++, rowInteger,"换手率 ", CellFormat.getCellFormat()));   
         
            
            JSONObject ob = JSONArray.parseArray(result.getContent()).getJSONObject(0);
             JSONArray arr =JSONArray.parseArray(ob.getString("hq"));
             if(arr!=null && !arr.isEmpty()) {
                 for (int i = 0; i < arr.size(); i++) {
                    colInteger = 0;
                    rowInteger++;
                    String e = arr.getString(i).replace("[", "").replace("]", "").replace("\"", "");
                    String[] eStrings = e.split(",");
                    for (int j = 0; j < eStrings.length; j++) {
                        if(Tools.isNumeric(eStrings[j])) {
                            worksheet.addCell(new jxl.write.Number(colInteger++,rowInteger,Double.parseDouble(eStrings[j]) ));
                        }else {
                            worksheet.addCell(new Label(colInteger++, rowInteger,eStrings[j], CellFormat.getCellFormat()));   
                        }
                    }
                                     
                }
             }              
             worksheet.setColumnView(0, 20);
             worksheet.setColumnView(1, 20);
             worksheet.setColumnView(2, 20);
             worksheet.setColumnView(3, 20);
             workbook.write();
             workbook.close();
             os.flush();
             os.close();
        }            
       
        return null;         
    }
    

    
    public Object getOneData(HttpServletRequest request, HttpServletResponse response) throws Exception { 
    	String keyValue =ToolsOfString.NulltoEmpty(request.getParameter("ID")); 
    	String sqlString = "SELECT  RoleId, Type,FullName,SortCode FROM base_role Where DeleteMark= 0  ";
    	sqlString = sqlString + " AND RoleId = '"+keyValue+"'";
        Map<String,Object>  map = baseImpl.getMap(sqlString);                 
        return R.succ(map);         
    }
    
    
    public Object getSharesData(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String FUNDSID =ToolsOfString.NulltoEmpty(request.getParameter("FUNDSID")); 
  
        String url = "http://fund.eastmoney.com/pingzhongdata/"+FUNDSID+".js?v=20160518155842"  ;
      
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");   
        HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
        if (result.getCode() == 200) {  
           
            String Content = result.getContent().toString();            
            String[] stocks = Content.split(";");
            String stockCodesNew = stocks[8];
            if(Tools.notEmpty(stockCodesNew)) {
               
                String[] stockCodesNews = stockCodesNew.replace("\"]", "").split("\",\"");
                List<String> Sharesids = new ArrayList<String>();
                for (int i = 0; i < stockCodesNews.length; i++) {
                    String s= stockCodesNews[i];
                    String e = s.substring(s.length()-6,s.length());
                    Sharesids.add(e);
                }
                List<Map<String, Object>> res = getSharesList(Sharesids);
                
                return R.succ(res);  
            }
        }                   
        return R.fail("無此數據");         
    }
    
    public List<Map<String, Object>> getSharesList(List<String> Sharesids ) throws Exception{
        List<Map<String, Object>> resList = new ArrayList<Map<String,Object>>();
        for (String sharesid : Sharesids) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json; charset=utf-8");             
            String url = "http://hq.sinajs.cn/list=sz"+sharesid;
            if(sharesid.startsWith("6")) {
                 url = "http://hq.sinajs.cn/list=sh"+sharesid;
            }
            HttpClientResult result = HttpClientUtils.doGet(url, params, null); 
            if (result.getCode() == 200) { 
                String[] Content = result.getContent().toString().split("=\"")[1].split(",");
                Map<String, Object> e =new HashMap<String, Object>();
                e.put("sharesid", sharesid);
                e.put("name", Content[0]);
                e.put("todayOpen", Content[1]);
                e.put("yesterdayClose", Content[2]);
                e.put("price", Content[3]);
                e.put("num", Content[8]);
                e.put("priceTotal", Content[9]);
                e.put("strdate", Content[30]);
                e.put("strtime", Content[31]);
                resList.add(e);
            }
        }
        return resList;
    }
    
    public Object getAPIFunds(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String funds =ToolsOfString.NulltoEmpty(request.getParameter("funds"));      
        String url = "http://fundgz.1234567.com.cn/js/"+funds+".js?rt=1463558676006"  ;
      
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");   
        HttpClientResult result = HttpClientUtils.doGet(url, params, null);             
        logger.info("請求gov預約信息：result==" + result.toString());
        if (result.getCode() == 200) {  
            String Content = result.getContent().toString().replace("jsonpgz(", "").replace(");", "");
            if(Tools.notEmpty(Content)) {
                return R.succ(Content);  
            }
        }                   
        return R.fail("無此數據");         
    }
    
    
    
    public Object delete(HttpServletRequest request, HttpServletResponse response) throws Exception {   
        String sharesid =ToolsOfString.NulltoEmpty(request.getParameter("SHAREID")); 
        Map<String, Object> searchcondition = new HashMap<String, Object>();
        searchcondition.put("SHAREID", sharesid);        
        Integer resInteger = baseImpl.deleteByCondition(searchcondition);
        return R.succ(resInteger);         
    }
    
  public Object save(HttpServletRequest request, HttpServletResponse response) throws Exception {  
      		
		String sql = "";
		Map<String, Object> searchcondition = ServletUtils.getsearchcondition(request);
	    String ID =ToolsOfString.NulltoEmpty(searchcondition.get("ID"));	    
        String FUNDSID =ToolsOfString.NulltoEmpty(searchcondition.get("FUNDSID")); 
        String SHAREID =ToolsOfString.NulltoEmpty(searchcondition.get("SHAREID"));
        String FullName =ToolsOfString.NulltoEmpty(searchcondition.get("FullName"));
        FullName =  java.net.URLDecoder.decode(FullName, "UTF-8");      
        
        if(Tools.notEmpty(ID)) {
        	//sql = "UPDATE base_role  SET FUNDSID = '"+FUNDSID+"',FullName = '"+FullName+"',SortCode = '" +SortCode+"'";
        	sql = sql + " WHERE ID ='"+ID+"'"; 
        }else {    
        	sql = "INSERT INTO shares(FUNDID,SHAREID,FULLNAME)VALUES";
        	sql = sql + " ('"+FUNDSID+"','"+SHAREID+"','"+FullName+"')"; 
        }
        Integer resInteger = baseImpl.save(sql);
        if(resInteger == 1) {
        	   return R.succ(); 
        }
        return R.fail();
       
    }
    
    
    
   
}
